{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
    "import seaborn as sns\n",
    "from sklearn.datasets import fetch_openml\n",
    "\n",
    "# 加载MNIST数据集\n",
    "def load_mnist_data():\n",
    "    print(\"正在加载MNIST数据集...\")\n",
    "    # 从openml获取MNIST数据集（70,000样本）\n",
    "    X, y = fetch_openml('mnist_784', version=1, return_X_y=True, as_frame=False)\n",
    "    print(f\"数据集加载完成，样本数: {X.shape[0]}, 特征数: {X.shape[1]}\")\n",
    "    return X, y\n",
    "\n",
    "# 数据预处理\n",
    "def preprocess_data(X, y):\n",
    "    print(\"正在进行数据预处理...\")\n",
    "    # 数据归一化\n",
    "    X = X / 255.0\n",
    "\n",
    "    # 划分训练集和测试集（使用10%数据作为测试集）\n",
    "    X_train, X_test, y_train, y_test = train_test_split(\n",
    "        X, y, test_size=0.1, random_state=42\n",
    "    )\n",
    "    print(f\"训练集大小: {X_train.shape[0]}, 测试集大小: {X_test.shape[0]}\")\n",
    "\n",
    "    return X_train, X_test, y_train, y_test\n",
    "\n",
    "# 训练随机森林模型\n",
    "def train_random_forest(X_train, y_train, n_estimators=100, max_depth=15):\n",
    "    print(f\"开始训练随机森林模型， estimators: {n_estimators}, max_depth: {max_depth}\")\n",
    "\n",
    "    # 初始化随机森林分类器\n",
    "    rf_model = RandomForestClassifier(\n",
    "        n_estimators=n_estimators,\n",
    "        max_depth=max_depth,\n",
    "        random_state=42,\n",
    "        n_jobs=-1  # 使用所有CPU核心\n",
    "    )\n",
    "\n",
    "    # 训练模型\n",
    "    rf_model.fit(X_train, y_train)\n",
    "    print(\"模型训练完成\")\n",
    "\n",
    "    return rf_model\n",
    "\n",
    "# 评估模型\n",
    "def evaluate_model(model, X_test, y_test):\n",
    "    print(\"正在评估模型性能...\")\n",
    "    # 预测\n",
    "    y_pred = model.predict(X_test)\n",
    "\n",
    "    # 计算准确率\n",
    "    accuracy = accuracy_score(y_test, y_pred)\n",
    "    print(f\"模型测试准确率: {accuracy:.4f}\")\n",
    "\n",
    "    # 生成分类报告\n",
    "    report = classification_report(y_test, y_pred)\n",
    "    print(\"分类报告:\\n\", report)\n",
    "\n",
    "    # 绘制混淆矩阵\n",
    "    cm = confusion_matrix(y_test, y_pred)\n",
    "    plt.figure(figsize=(10, 8))\n",
    "    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n",
    "                xticklabels=np.unique(y_test),\n",
    "                yticklabels=np.unique(y_test))\n",
    "    plt.xlabel('预测标签')\n",
    "    plt.ylabel('真实标签')\n",
    "    plt.title('混淆矩阵')\n",
    "    plt.tight_layout()\n",
    "    plt.savefig('confusion_matrix.png')\n",
    "    print(\"混淆矩阵已保存为confusion_matrix.png\")\n",
    "\n",
    "    return accuracy, report, cm\n",
    "\n",
    "# 可视化预测结果\n",
    "def visualize_predictions(model, X_test, y_test, n_samples=10):\n",
    "    print(f\"可视化{ n_samples }个样本的预测结果...\")\n",
    "    plt.figure(figsize=(15, 4))\n",
    "\n",
    "    # 随机选择n_samples个样本\n",
    "    indices = np.random.choice(len(X_test), n_samples, replace=False)\n",
    "\n",
    "    for i, idx in enumerate(indices):\n",
    "        plt.subplot(1, n_samples, i+1)\n",
    "        # 重塑为28x28图像\n",
    "        img = X_test[idx].reshape(28, 28)\n",
    "        plt.imshow(img, cmap='gray')\n",
    "\n",
    "        # 获取预测结果\n",
    "        pred = model.predict([X_test[idx]])[0]\n",
    "        true_label = y_test[idx]\n",
    "\n",
    "        plt.title(f\"真实: {true_label}\\n预测: {pred}\")\n",
    "        plt.axis('off')\n",
    "\n",
    "    plt.tight_layout()\n",
    "    plt.savefig('predictions_visualization.png')\n",
    "    print(\"预测结果可视化已保存为predictions_visualization.png\")\n",
    "\n",
    "# 主函数\n",
    "def main():\n",
    "    # 加载数据\n",
    "    X, y = load_mnist_data()\n",
    "\n",
    "    # 数据预处理\n",
    "    X_train, X_test, y_train, y_test = preprocess_data(X, y)\n",
    "\n",
    "    # 训练模型\n",
    "    rf_model = train_random_forest(X_train, y_train, n_estimators=100, max_depth=15)\n",
    "\n",
    "    # 评估模型\n",
    "    accuracy, report, cm = evaluate_model(rf_model, X_test, y_test)\n",
    "\n",
    "    # 可视化预测结果\n",
    "    visualize_predictions(rf_model, X_test, y_test, n_samples=10)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
